import type { SysDict } from '@/apis/system/sysDictApi'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { sysDictApi } from '@/apis/system/sysDictApi'

export const useDictStore = defineStore('dict', () => {
  const dictMap = ref<Record<string, SysDict[]>>({})

  async function loadDict(dictCode: string) {
    if (dictMap.value[dictCode] === undefined) {
      dictMap.value[dictCode] = []
      dictMap.value[dictCode] = (await sysDictApi.queryTreeByRootCode(dictCode)).filter(d => d !== undefined)
    }
    return dictMap.value[dictCode]
  }

  function getDict(rootCode: string, dictCode?: string): SysDict | undefined {
    return _getDict(dictMap.value[rootCode], dictCode)
  }

  function _getDict(dicts: SysDict[], dictCode?: string): SysDict | undefined {
    if (dicts === undefined) {
      return undefined
    }
    for (const dict of dicts) {
      if (dict.dictCode === dictCode) {
        return dict
      }
      else if (dict.children !== undefined) {
        const child = _getDict(dict.children, dictCode)
        if (child !== undefined) {
          return child
        }
      }
    }
  }

  function getFlatDict(rootCode: string, dictCode?: string): SysDict | undefined {
    return flatDicts(rootCode).find(d => d.dictCode === dictCode)
  }

  function flatDicts(rootCode: string): SysDict[] {
    return _flatDicts(dictMap.value[rootCode], [])
  }

  function _flatDicts(dicts: SysDict[], paths: SysDict[]): SysDict[] {
    const result: SysDict[] = []
    for (let i = 0; i < dicts.length; i++) {
      const dict = dicts[i]
      if (dict.children && dict.children.length > 0) {
        result.push(..._flatDicts(dict.children, [...paths, dict]))
        result.push({ ...dict })
      }
      else {
        result.push({
          ...dict,
          dictName: [...paths, dict].map(d => d.dictName).join('/'),
        })
      }
    }
    return result
  }

  return { dictMap, loadDict, getDict, flatDicts, getFlatDict }
})
